<template>
  <Row justify="center">
    <!--      点击提交反馈和录音后的加载动图-->
    <Spin size="large" fix v-if="spinShow"></Spin>
    <Col flex="auto">
      <div>
        <row justify="center">
          <ButtonGroup vertical>
            <br>
            <Alert :style="display1" show-icon>您当前暂无面试</Alert>
            <Alert :style="display3" show-icon>面试已结束</Alert>
            <Alert :style="display2" show-icon>面试正在进行</Alert>
            <Button class="tag-top" type="info" ghost>面试官：{{ Interviewer_name }}</Button>
            <br>
            <Button class="tag-top" type="info" ghost>面试者：{{ Interviewee_name }}</Button>
            <br>
            <Button class="tag-top" type="info" ghost>面试时间：
              {{ Interview_time_year }}年{{ Interview_time_month }}月{{ Interview_time_day }}日
              {{ Interview_time_hours }}:{{ Interview_time_minutes }}
            </Button>
            <br>
          </ButtonGroup>&nbsp;

        </row>

      </div>
      <div class="tag-bottom">
        <row justify="center">
          <Button @click="download">下载文档</Button>
          <br>
          <!--          添加加载动图-->
          <Col :style="display4" span="8">
            <Spin fix>
              <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
              <div>Loading</div>
            </Spin>
          </Col>
        </row>
      </div>

      <Row justify="center" style="padding-top:1%">
        <Button type="success" @click="btnStart">开始面试</Button>&nbsp;
        <Button type="error" @click="btnStop">结束面试</Button>&nbsp;
        <!--        点击弹出一个抽屉-->
        <Button @click="value1 = true" type="primary">查看历史反馈</Button>
        <Drawer title="历史反馈内容" width="50" :closable="false" v-model="value1">
          <div v-for="item in InterviewerFeedbacks">
            面试时间：
            {{ new Date(item[0]).getFullYear() }}年
            {{
              new Date(item[0]).getMonth() < 9 ? '0' + (new Date(item[0]).getMonth() + 1) : (new Date(item[0]).getMonth() + 1)
            }}月
            {{
              new Date(item[0]).getDate() < 10 ? '0' + (new Date(item[0]).getDate()) : new Date(item[0]).getDate()
            }}日
            {{
              new Date(item[0]).getHours() < 10 ? '0' + (new Date(item[0]).getHours()) : new Date(item[0]).getHours()
            }}：
            {{
              new Date(item[0]).getMinutes() < 10 ? '0' + (new Date(item[0]).getMinutes()) : new Date(item[0]).getMinutes()
            }}<br>
            面试者姓名：{{ item[1] }}<br>
            面试者评价：{{ item[2] }}<br><br>
          </div>
        </Drawer>
      </Row>
      <!-- 录音 -->
      <Row justify="center" style="padding-top: 20px;">
        <Card style="width:400px;">
          <Row justify="center" style="padding-top:1%">
            <h3>录音时长：{{ recorder && recorder.duration.toFixed(2) }}</h3>
          </Row>
          <Row justify="center" style="padding-top:0.5%">
            <Button type="primary" @click="handleStart()">开始录音</Button>&nbsp;
            <Button type="info" @click="handlePause()">暂停录音</Button>&nbsp;
            <Button type="primary" @click="handleResume()">继续录音</Button>&nbsp;
            <Button type="info" @click="handleStop()">停止录音</Button>&nbsp;
            <Button type="primary" @click="handleDestroy()">重新录音</Button>&nbsp;
            <Button type="info" @click="downWAV()">下载录音</Button>&nbsp;
          </Row>

        </Card>
      </Row>
    </Col>

    <!-- 反馈 -->
    <Col flex="100px">
      <Row justify="center" style="padding-top:20px;padding-right: 20px;">
        <Col>
          <Input v-model="value_text" maxlength="400" show-word-limit type="textarea" :rows="10"
                 placeholder="给出您最珍贵的反馈......" style="width: 400px;"/>

          <div style="padding: 20px;">
            <Button @click="allValue" style="background-color: rgb(51, 153, 255);" type="success" long>提交反馈和录音</Button>
          </div>
        </Col>
      </Row>
    </Col>
  </Row>
</template>

<script>
import Recorder from 'js-audio-recorder'

export default {
  name: 'Interviewer',
  data () {
    return {
      spinShow: false,
      Interviewee_name: 'Interviewee_name',
      Interviewer_name: 'Interviewer_name',
      Interview_time: 'Interview_time',
      status: '',
      id: '',
      Interview_time_year: '',
      Interview_time_month: '',
      Interview_time_day: '',
      Interview_time_hours: '',
      Interview_time_minutes: '',

      // 录音时间和对象
      recorder: new Recorder(),
      timer: null,

      // 录音
      value_text: '',

      // 抽屉
      InterviewerFeedbacks: [],
      InterviewerFeedback: 'InterviewerFeedback',
      value1: false,

      //  隐藏提示
      display1: 'display:none',
      display2: 'display:none',
      display3: 'display:none',

      //隐藏加载动图
      display4: 'display:none',

      // 判断是否上传（提交）成功
      isSubmitRecord: false,
      isSubmitFeedback: false,
    }
  },
  // 加载该页面时，执行以下操作
  created () {
    this.getData('/api/interviewer', this.getInterviewer)
    // this.getData('/api/interviewer/drawer', this.getInterviewerFeedback)
  },

  methods: {

    // 从后端获取数据
    getData (url, func) {
      fetch(url).then(
        (response) => {
          if (response.status === 200) {
            console.log(response.status)
            return response.json()
          }
          throw new Error('异常')
        }
      ).then(
        func
      ).catch(
        (reject) => {
          console.log(reject)
        }
      )
    },
    // 反馈和录音请求
    async allValue () {
      await fetch('api/v1/interviewerFeedback', {
        method: 'post',
        body: JSON.stringify({
          'interviewerFeedback': this.value_text,
          'id': this.id,
        }),
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then((data) => {
          if (data.status === 200) {
            this.isSubmitFeedback = true
          }
        })

      // 上传录音
      if (this.recorder == null || this.recorder.duration === 0) {
        this.$Message.error('请先录音')
        this.$Message({
          message: '请先录音',
          type: 'error'
        })
        return false
      }
      this.recorder.pause() // 暂停录音
      this.timer = null
      console.log('上传录音')// 上传录音

      const formData = new FormData()
      const blob = this.recorder.getWAVBlob()// 获取wav格式音频实际数据
      // 此处获取到blob对象后需要设置fileName满足当前项目上传需求，其它项目可直接传把blob作为file塞入formData
      const newbolb = new Blob([blob], { type: 'audio/wav' })
      const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')
      formData.append('file', fileOfBlob)
      const url = window.URL.createObjectURL(fileOfBlob)
      this.src = url
//点击提交反馈和录音后的加载动图
      this.spinShow = true
      await fetch('api/v1/uploadRecord', {
        method: 'post',
        body: formData,
      })
        .then((data) => {
          if (data.status === 200) {
            this.isSubmitRecord = true
          }
        }).finally(() => {
          this.spinShow = false
        })

      // 判断是否提交成功
      if (this.isSubmitFeedback == true && this.isSubmitRecord == true) {
        alert('提交成功！')
      } else {
        alert('提交失败！')
      }

    },
    // 获取面试官姓名、面试者姓名、面试时间、面试文档、面试状态、面试id
    getInterviewer (response) {
      console.log(response)
      this.Interviewer_name = response['usernameInterviewer']
      this.Interviewee_name = response['usernameInterviewee']
      var InterviewDate = new Date(response['interviewTime'])
      this.status = response['status']
      this.id = response['interviewId']
      //显示”您当前暂无面试“提示框,关闭”面试正在进行“、”面试已结束“提示框
      if (response['interviewTime'] === null) {
        this.display1 = ''
        this.display2 = 'display:none'
        this.display3 = 'display:none'
      } else {
        this.Interview_time_year = InterviewDate.getFullYear()
        this.Interview_time_month = InterviewDate.getMonth() < 9 ? '0' + (InterviewDate.getMonth() + 1) : (InterviewDate.getMonth() + 1)
        this.Interview_time_day = InterviewDate.getDate() < 10 ? '0' + InterviewDate.getDate() : InterviewDate.getDate()
        this.Interview_time_hours = InterviewDate.getHours() < 10 ? '0' + InterviewDate.getHours() : InterviewDate.getHours()
        this.Interview_time_minutes = InterviewDate.getMinutes() < 10 ? '0' + InterviewDate.getMinutes() : InterviewDate.getMinutes()
      }
    },
    // 获取反馈信息
    getInterviewerFeedback (response) {
      for (let i = 0; i < response.length; i++) {
        this.InterviewerFeedbacks[i] = response[i]// 取出一个子列表
      }
    },
    Jump () {
      this.$router.go(-1)
    },
    // 录音
    handleStart () {
      this.recorder = new Recorder()
      Recorder.getPermission().then(() => {
        this.recorder.start() // 开始录音
      }, (error) => {
        this.$Message.info('请先允许该网页使用麦克风')
        // this.$Message({
        //   message:'请先允许该网页使用麦克风',
        //   type:'info'
        // });
      })
    },
    handlePause () {
      this.recorder.pause() // 暂停录音
    },
    handleResume () {
      this.recorder.resume() // 恢复录音
    },
    handleStop () {
      this.recorder.stop() // 停止录音
    },
    handleDestroy () {
      this.recorder.destroy() // 重新录音
      this.timer = null
    },
    downWAV () {
      // downloadWAV给有个文件名
      this.recorder.downloadWAV('新录音')
    },
    //显示”面试正在进行“提示框，并更改数据库面试状态
    btnStart () {
      this.display3 = 'display:none'
      if (this.display1 === '') {
        this.display2 = 'display:none'
      } else {
        this.display2 = ''
      }
      fetch('/api/interviewer/start/status', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ interviewsId: this.id })
      })
    },
    //关闭”面试正在进行“提示框，显示”面试已结束“提示框，并更改数据库面试状态
    btnStop () {
      this.display2 = 'display:none'
      if (this.display1 === '') {
        this.display3 = 'display:none'
      } else {
        this.display3 = ''
      }
      fetch('/api/interviewer/stop/status', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ interviewsId: this.id })
      })
    },
    //下载文档
    download () {
      if (this.id === '') {
        this.$Message.error('请重新登录账号')
        this.$router.push('/login')
        return
      }
      //显示加载动图
      this.display4 = ''
      fetch('/api/interviewer/pdf/' + this.id)
        .then((res) => {
          if (res.status === 200) {
            return res.json()
          }
          throw new Error('Error')
        }).then((json) => {
        let b64 = atob(json['key'])
        let n = b64.length
        let arr = new Uint8Array(n)
        for (let i = 0; i < n; i++) {
          arr[i] = b64.charCodeAt(i)
        }
        let downloadFile = new File([arr], 'pdf' + this.id + '.pdf', { type: 'application/pdf' })
        console.log(downloadFile)
        //创建下载路径
        let url = window.URL.createObjectURL(downloadFile)
        //创建a标签
        let a = document.createElement('a')
        a.href = url
        a.target = '_Blank'
        document.body.appendChild(a)
        a.click()
        //下载完成移除a标签
        document.body.removeChild(a)
        //释放连接
        window.URL.revokeObjectURL(url)
      }).catch((error) => {
        console.log(error)
        this.$Message.error('下载失败，请检查网络设置')
      }).finally(() => {
        //  隐藏加载动图
        this.display4 = 'display:none'
      })
    }
  }
}
</script>

<style scoped>
/*加载动图样式*/
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}

@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.top_bar {
  background: #506b9e;
  width: 100%;
  height: 40px;
}

.tag-text {
  width: 36%;
  height: 100%;
}

/* .tag-top {
  width: 80%;
  height: 8%;
} */

</style>
